package server

import (
	"fmt"

	"github.com/TarsCloud/TarsGo/tars"
	"github.com/TarsCloud/TarsGo/tars/util/conf"
	"github.com/wzh200x/gateServer/network"
	GateServerProtocol "github.com/wzh200x/hyperNexus/hyperNexusProtocol/gateServerProtocol"
)

// GateServer 定义Web服务器结构体
type GateServer struct {
	GNetServer *network.GateGNetServer
}

// ServerApp 是全局服务器实例
var ServerApp = &GateServer{}

// Init 初始化服务器
func (gs *GateServer) Init(comm *tars.Communicator, sConf *conf.Conf) error {
	// 初始化tars
	gs.RegisterTarsObj()

	tars.GetLogger("").Infof("GateServer initialized successfully")
	// 这里的配置可以根据实际需求进行调整
	gs.GNetServer = network.NewGateGNetServer(sConf)
	return nil
}

// InitFinish 完成初始化后的操作
func (gs *GateServer) InitFinish() error {
	// 初始化并启动gnet服务器
	go func() {
		if err := gs.GNetServer.Start(); err != nil {
			tars.GetLogger("").Errorf("Failed to start gnet server: %v", err)
		}
	}()

	return nil
}

// Info 返回服务器信息
func (gs *GateServer) Info() string {
	return fmt.Sprintf(`server: %s version: %s`, "GateServer", "0.0.1")
}

// Name 返回服务器名称
func (gs *GateServer) Name() string {
	return "GateServer"
}

func (gs *GateServer) Stop() error {
	return nil
}

// RegisterTarsObj 注册Tars对象
func (gs *GateServer) RegisterTarsObj() {
	// Get server config
	cfg := tars.GetServerConfig()
	// // New servant imp
	imp := new(GateServerOperateImp)
	app := new(GateServerProtocol.GateServer)
	// Register Servant
	app.AddServantWithContext(imp, cfg.App+"."+cfg.Server+".GateServerOperateObj")
}
